<!doctype html>



  


<html class="theme-next mist use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />















  
  
    
  
  <link href="//cdn.jsdelivr.net/fancybox/2.1.5/jquery.fancybox.min.css" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






  

<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.6.2/css/font-awesome.min.css" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.0" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="Python 爬虫," />








  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.0" />






<meta name="description" content="在python中使用requests简化了网络请求，在使用requests之前需要pip install requests来安装requests,requests中文手册是一个很好的入门资料。制作爬虫需要对html的结构有一定的了解，同时使用正则表达式原生匹配的爬虫也会随网页结构的改变而失效，所以若使下述代码无效，请分析网页的结构是否发生了改变。抓取网页：极客学院视频库网页爬取效果：# -*-co">
<meta property="og:type" content="article">
<meta property="og:title" content="python爬虫之requests">
<meta property="og:url" content="https://zitongchen.github.io/2017/03/12/python爬虫之requests/index.html">
<meta property="og:site_name" content="Tony's Notes">
<meta property="og:description" content="在python中使用requests简化了网络请求，在使用requests之前需要pip install requests来安装requests,requests中文手册是一个很好的入门资料。制作爬虫需要对html的结构有一定的了解，同时使用正则表达式原生匹配的爬虫也会随网页结构的改变而失效，所以若使下述代码无效，请分析网页的结构是否发生了改变。抓取网页：极客学院视频库网页爬取效果：# -*-co">
<meta property="og:image" content="http://img.blog.csdn.net/20170302100144106?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQveml0b25nQ2hlbg==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast">
<meta property="og:updated_time" content="2017-03-15T13:43:27.492Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="python爬虫之requests">
<meta name="twitter:description" content="在python中使用requests简化了网络请求，在使用requests之前需要pip install requests来安装requests,requests中文手册是一个很好的入门资料。制作爬虫需要对html的结构有一定的了解，同时使用正则表达式原生匹配的爬虫也会随网页结构的改变而失效，所以若使下述代码无效，请分析网页的结构是否发生了改变。抓取网页：极客学院视频库网页爬取效果：# -*-co">
<meta name="twitter:image" content="http://img.blog.csdn.net/20170302100144106?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQveml0b25nQ2hlbg==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    sidebar: {"position":"left","display":"post","offset":12,"offset_float":0,"b2t":false,"scrollpercent":false},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://zitongchen.github.io/2017/03/12/python爬虫之requests/"/>





  <title> python爬虫之requests | Tony's Notes </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  














  
  
    
  

  <div class="container one-collumn sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Tony's Notes</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
    <link itemprop="mainEntityOfPage" href="https://zitongchen.github.io/2017/03/12/python爬虫之requests/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Tony">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avater.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Tony's Notes">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                python爬虫之requests
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-03-12T00:00:00+08:00">
                2017-03-12
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Python/" itemprop="url" rel="index">
                    <span itemprop="name">Python</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/2017/03/12/python爬虫之requests/" class="leancloud_visitors" data-flag-title="python爬虫之requests">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数 </span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          

          

        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>在python中使用requests简化了网络请求，在使用requests之前需要<code>pip install requests</code>来安装requests,<a href="http://docs.python-requests.org/zh_CN/latest/user/quickstart.html#id2" target="_blank" rel="external">requests中文手册</a>是一个很好的入门资料。<br>制作爬虫需要对html的结构有一定的了解，同时使用正则表达式原生匹配的爬虫也会随网页结构的改变而失效，所以若使下述代码无效，请分析网页的结构是否发生了改变。<br>抓取网页：<a href="http://www.jikexueyuan.com/course/?pageNum=1" target="_blank" rel="external">极客学院视频库网页</a><br>爬取效果：<br><img src="http://img.blog.csdn.net/20170302100144106?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQveml0b25nQ2hlbg==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast" alt="图片效果"><br><figure class="highlight python"><table><tr><td class="code"><pre><div class="line"><span class="comment"># -*-coding:utf-8 -*-</span></div><div class="line"><span class="keyword">import</span> requests</div><div class="line"><span class="keyword">import</span> re</div><div class="line"><span class="keyword">import</span> sys</div><div class="line"></div><div class="line"><span class="string">'''</span></div><div class="line"> 1.先获取整个网页</div><div class="line"> 2.获取整个网页中的课程块</div><div class="line"> 3.通过正则表达使获取想要的特定内容</div><div class="line">'''</div><div class="line"><span class="class"><span class="keyword">class</span> <span class="title">spider</span><span class="params">(object)</span>:</span></div><div class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self)</span>:</span></div><div class="line">        print(<span class="string">u'开始爬取内容...'</span>)</div><div class="line"></div><div class="line"></div><div class="line">    <span class="comment"># 用于获取网页的源代码</span></div><div class="line">    <span class="function"><span class="keyword">def</span> <span class="title">getsource</span><span class="params">(self, url)</span>:</span></div><div class="line">        html = requests.get(url)</div><div class="line">        html.encoding = <span class="string">'utf-8'</span></div><div class="line">        <span class="keyword">return</span> html.text</div><div class="line"></div><div class="line">    <span class="comment"># 改变链接中的页码数</span></div><div class="line">    <span class="function"><span class="keyword">def</span> <span class="title">changepage</span><span class="params">(self, url, total_page)</span>:</span></div><div class="line">        now_page = int(re.search(<span class="string">'pageNum=(\d+)'</span>, url, re.S).group(<span class="number">1</span>))  <span class="comment"># 返回页码数</span></div><div class="line">        page_group = []</div><div class="line">        <span class="keyword">for</span> i <span class="keyword">in</span> range(now_page, total_page + <span class="number">1</span>):</div><div class="line">            link = re.sub(<span class="string">'pageNum=\d+'</span>, <span class="string">'pageNum=%s'</span> % i, url, re.S)  <span class="comment"># 替换url中的页码数</span></div><div class="line">            page_group.append(link)</div><div class="line">        <span class="keyword">return</span> page_group</div><div class="line"></div><div class="line">    <span class="comment"># 抓取每个课程块消息</span></div><div class="line">    <span class="function"><span class="keyword">def</span> <span class="title">geteveryclass</span><span class="params">(self, source)</span>:</span></div><div class="line">        everyclass = re.findall(<span class="string">'(&lt;li id=".*?&lt;/li&gt;)'</span>, source, re.S)</div><div class="line">        <span class="keyword">return</span> everyclass</div><div class="line"></div><div class="line">    <span class="comment"># 从课程块中得到我们想要的信息</span></div><div class="line">    <span class="function"><span class="keyword">def</span> <span class="title">getinfo</span><span class="params">(self, eachclass)</span>:</span></div><div class="line">        info = &#123;&#125;</div><div class="line">        info[<span class="string">'title'</span>] = re.search(<span class="string">'.*&gt;(.*?)&lt;/a&gt;&lt;/h2&gt;'</span>, eachclass, re.S).group(<span class="number">1</span>)</div><div class="line">        info[<span class="string">'content'</span>] = re.search(<span class="string">'.*&gt;(.*?)&lt;/p&gt;'</span>, eachclass, re.S).group(<span class="number">1</span>).strip()</div><div class="line">        timeandlevel = re.findall(<span class="string">'&lt;em&gt;(.*?)&lt;/em&gt;'</span>, eachclass, re.S)</div><div class="line">        classtime = timeandlevel[<span class="number">0</span>].split()  <span class="comment"># 截取字符中的空格</span></div><div class="line">        info[<span class="string">'classtime'</span>] = classtime[<span class="number">0</span>] + classtime[<span class="number">1</span>]</div><div class="line">        info[<span class="string">'classlevel'</span>] = timeandlevel[<span class="number">1</span>]</div><div class="line">        info[<span class="string">'learnnum'</span>] = re.search(<span class="string">'"learn-number"&gt;(.*?)&lt;/em&gt;'</span>, eachclass, re.S).group(<span class="number">1</span>)</div><div class="line">        <span class="keyword">return</span> info</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">def</span> <span class="title">saveinfo</span><span class="params">(self, classinfo)</span>:</span></div><div class="line">        f = open(<span class="string">'info.txt'</span>, <span class="string">'a'</span>, encoding=<span class="string">'utf-8'</span>)</div><div class="line">        <span class="keyword">for</span> each <span class="keyword">in</span> classinfo:</div><div class="line">            f.writelines(<span class="string">'title:'</span> + each[<span class="string">'title'</span>] + <span class="string">'\n'</span>)</div><div class="line">            f.writelines(<span class="string">'content:'</span> + each[<span class="string">'content'</span>] + <span class="string">'\n'</span>)</div><div class="line">            f.writelines(<span class="string">'classtime:'</span> + each[<span class="string">'classtime'</span>] + <span class="string">'\n'</span>)</div><div class="line">            f.writelines(<span class="string">'classlevel:'</span> + each[<span class="string">'classlevel'</span>] + <span class="string">'\n'</span>)</div><div class="line">            f.writelines(<span class="string">'learnnum:'</span> + each[<span class="string">'learnnum'</span>] + <span class="string">'\n\n'</span>)</div><div class="line">        f.close()</div><div class="line"><span class="keyword">if</span> __name__ == <span class="string">'__main__'</span>:</div><div class="line">    classinfo = []</div><div class="line">    url = <span class="string">'http://www.jikexueyuan.com/course/?pageNum=2'</span></div><div class="line">    jikespider = spider()</div><div class="line">    all_links = jikespider.changepage(url, <span class="number">20</span>)</div><div class="line">    print(all_links)</div><div class="line">    <span class="keyword">for</span> link <span class="keyword">in</span> all_links:</div><div class="line">        print(<span class="string">u'正在处理页面：'</span> + link)</div><div class="line">        html = jikespider.getsource(link)</div><div class="line">        everyclass = jikespider.geteveryclass(html)</div><div class="line">        <span class="keyword">for</span> each <span class="keyword">in</span> everyclass:</div><div class="line">            info = jikespider.getinfo(each)</div><div class="line">            classinfo.append(info)</div><div class="line">    jikespider.saveinfo(classinfo)</div></pre></td></tr></table></figure></p>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>


    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Python-爬虫/" rel="tag"># Python 爬虫</a>
          
        </div>
      

      
        
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2017/03/12/在python中使用正则表达式/" rel="next" title="在python中使用正则表达式">
                <i class="fa fa-chevron-left"></i> 在python中使用正则表达式
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2017/03/12/python爬虫之xpath/" rel="prev" title="python爬虫之xpath">
                python爬虫之xpath <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>

          
          </div>
          


          
  <div class="comments" id="comments">
    
      <div id="uyan_frame"></div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      

      <section class="site-overview sidebar-panel sidebar-panel-active">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/images/avater.png"
               alt="Tony" />
          <p class="site-author-name" itemprop="name">Tony</p>
           
              <p class="site-description motion-element" itemprop="description">学习技术，分享技术...</p>
          
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
              <a href="/archives">
                <span class="site-state-item-count">29</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              <a href="/categories/index.html">
                <span class="site-state-item-count">11</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-tags">
              <a href="/tags/index.html">
                <span class="site-state-item-count">25</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/zitongchen" rel="external nofollow" target="_blank" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>
                  
                  GitHub
                </a>
              </span>
            
          
        </div>

        
        

        
        

        


      </section>

      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2017</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Tony</span>
</div>


<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io" rel="external nofollow">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next" rel="external nofollow">
    NexT.Mist
  </a>
</div>


        

        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    
    
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  




  
  <script type="text/javascript" src="//cdn.jsdelivr.net/jquery/2.1.3/jquery.min.js"></script>

  
  <script type="text/javascript" src="//cdn.jsdelivr.net/fastclick/1.0.6/fastclick.min.js"></script>

  
  <script type="text/javascript" src="//cdn.jsdelivr.net/jquery.lazyload/1.9.3/jquery.lazyload.min.js"></script>

  
  <script type="text/javascript" src="//cdn.jsdelivr.net/velocity/1.2.3/velocity.min.js"></script>

  
  <script type="text/javascript" src="//cdn.jsdelivr.net/velocity/1.2.3/velocity.ui.min.js"></script>

  
  <script type="text/javascript" src="//cdn.jsdelivr.net/fancybox/2.1.5/jquery.fancybox.pack.js"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.0"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.0"></script>



  



  




	





  





  
    

    
      <!-- UY BEGIN -->
      <script type="text/javascript" src="http://v2.uyan.cc/code/uyan.js?uid=2130825"></script>
      <!-- UY END -->
    
  





  



  
  

  

  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.1.js"></script>
  <script>AV.initialize("4wyUmphSKE5wrQGHEh5Js0bk-gzGzoHsz", "oTOHrhMuED5U0oqV2KrRMGF0");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  


  
</body>
</html>
